<?php
// public/materials/delete.php
declare(strict_types=1);
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../includes/layout.php';
require_once __DIR__.'/../../includes/flash.php';
require_once __DIR__.'/../../includes/csrf.php';

require_login();
$user = current_user();

// only admin/hr/trainer
if (!in_array($user['role'], ['admin','hr','trainer'], true)) {
  set_flash('error', 'Access denied.');
  header('Location: index.php');
  exit;
}

global $pdo;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  verify_csrf();   // ✅ use this instead of require_csrf()
  $id = (int)($_POST['id'] ?? 0);

  $stmt = $pdo->prepare("SELECT * FROM materials WHERE id=?");
  $stmt->execute([$id]);
  $material = $stmt->fetch();

  if ($material) {
    // delete file if pdf exists
    if ($material['file_path']) {
      $file = __DIR__.'/../../uploads/'.$material['file_path'];
      if (is_file($file)) {
        unlink($file);
      }
    }
    $del = $pdo->prepare("DELETE FROM materials WHERE id=?");
    $del->execute([$id]);
    set_flash('success', 'Material deleted.');
  } else {
    set_flash('error', 'Material not found.');
  }
  header('Location: index.php');
  exit;
}
